<template>
<!-- 制剂原材料消耗 -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  abel-width="100px" :rules="rules">
      <el-form-item label="选择时间" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="StartDatetions"

        ></el-date-picker>
      </el-form-item>


      <el-form-item label="药品名称">
        <el-input
          v-model="queryParams.searchKey" placeholder="请输入药品名称/编码" clearable size="small" @keyup.enter.native="getList"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col>
        <el-button type="primary"  icon="el-icon-my-print" @click="print" >打印</el-button>
        <el-button type="primary"  icon="el-icon-my-export" @click="validateData('queryForm',excelExport)" >导出</el-button>
        <column-hidden-toolbar  @queryTable="getList" :columns="columnList"></column-hidden-toolbar>
      </el-col>
    </el-row>

    <el-row :gutter="24">

      <!--   表单主体     -->
      <el-table v-loading="tableLoading" ref="multipleTable" :data="tableData" show-summary :summary-method="getSummaries" @sort-change="handleSortChange" :border="true">
      <el-table-column :label="columnList[0].label" v-if="columnList[0].visible" type="index"   align="center"/>
        <el-table-column :label="columnList[1].label" v-if="columnList[1].visible" :prop="columnList[1].prop" align="center" :sortable="columnList[1].sortable" />
        <el-table-column :label="columnList[2].label" v-if="columnList[2].visible" :prop="columnList[2].prop" align="center" :sortable="columnList[2].sortable" />
        <el-table-column :label="columnList[3].label" v-if="columnList[3].visible" :prop="columnList[3].prop" align="center" :sortable="columnList[3].sortable" />
        <el-table-column :label="columnList[4].label" v-if="columnList[4].visible" :prop="columnList[4].prop" align="center" :sortable="columnList[4].sortable" />
        <el-table-column :label="columnList[5].label" v-if="columnList[5].visible" :prop="columnList[5].prop" align="center" :sortable="columnList[5].sortable" />
        <el-table-column :label="columnList[6].label" v-if="columnList[6].visible" :prop="columnList[6].prop" align="center" :sortable="columnList[6].sortable" />
      </el-table>
    </el-row>





  </div>
</template>


<script>

import Template from '@/views/tool/template'

import {
  preparationRawMaterialConsumptionExportRequest,
  preparationRawMaterialConsumptionListRequest
} from '@/api/business/preparation'
import { run_print } from '@/utils/grid/grwebapp'
import ColumnHiddenToolbar from '@/components/RightToolbar/ColumnHiddenToolbar.vue'
import { downloadYsglByFileName } from '@/utils/request'
import { Loading } from 'element-ui'

export default {
  name: 'preparationRawMaterialConsumption',
  components: { ColumnHiddenToolbar, Template },
  dicts: ['his_pharmacy'],
  data() {
    return {
      queryParams: {
        // 时间区间
        dateRange:[],
        // 搜索
        searchKey:'',
        isAsc:'',
        orderByColumn:''

      },
      // 表单校验
      rules: {

        dateRange: [{
          type: 'array',
          required: true,
          message: '请选择日期区间',
          fields: {
            0: {
              // type: 'date', //tpye类型试情况而定,所以如果返回的是date就改成date
              required: true,
              trigger: "change",
              message: '请选择开始日期'
            },
            1: {
              // type: 'date',
              required: true,
              trigger: "change",
              message: '请选择结束日期'
            }
          }
        }],

      },
      //时间限制
      StartDatetions: {
        disabledDate: time => {
          return time.getTime() > new Date();
        }
      },
      tableData: [
      ],
      printData:{},
      tableLoading: false,

      // 列信息
      columnList: [
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `药品名称规格`, visible: true, prop: 'drugName', sortable: 'drugName' },
        { key: 2, label: `单位`, visible: true, prop: 'drugUnit', sortable: 'drugUnit' },
        { key: 3, label: `数量`, visible: true, prop: 'consumeNum', sortable: 'consumeNum' },
        { key: 4, label: `批发价`, visible: true, prop: 'byprice', sortable: 'byprice' },
        { key: 5, label: `批发金额`, visible: true, prop: 'bypriceCount', sortable: 'bypriceCount' },
        { key: 6, label: `零售价`, visible: true, prop: 'price', sortable: 'price' },
      ],
      // 汇总列
      summaryPropertyList:[
        "bypriceCount"
      ],
      // 排序缓存
      sortField: {},
    }

  },

  created() {

  },
  methods: {
    validateData(formName,callback) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          callback();
        } else {
          return false;
        }
      })
    } ,
    /** 查询 */
    getList() {
      let formName = "queryForm"
      this.validateData(formName,this.handleRequest)
    },
    /** 实际查询  */
    handleRequest() {
      this.loading = true;
      //校验成功
      this.queryParams.startTime = this.queryParams.dateRange[0]
      this.queryParams.endTime = this.queryParams.dateRange[1]
      preparationRawMaterialConsumptionListRequest(this.queryParams).then(res => {
        if (res.code === 200) {
          this.tableData = res.data;

          this.loading = false;
        }

      }).catch(error => {
        this.loading = false;
      })
    },
    /** 重置查询条件 */
    resetQuery(){
      Object.assign(this.$data, this.$options.data())
      this.resetForm("queryForm");
    },
    /** 表格汇总行  */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        let property = column.property
        const values = data.map(item => Number(item[property]));
        //求和
        if (this.summaryPropertyList.includes(property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0).toFixed(2);
        } else {
        }
      });
      return sums;
    },
    /** 排序  */
    handleSortChange({ order, prop }) {
      // 触发的排序和缓存的排序相同时，取消该字段的排序
      if (!order || this.sortField[prop] === order) {
        this.sortField[prop] = null
      } else {
        this.sortField[prop] = order
      }
      this.orderBys = []
      let direction = ''
      for (const i in this.sortField) {
        if (this.sortField[i] == 'ascending') {
          direction = 'ASC'
        } else if (this.sortField[i] == 'descending') {
          direction = 'DESC'
        }else if (this.sortField[i] == null){
          continue;
        }
        this.orderBys.push({
          "column": i,
          "direction": direction
        })
      }
      let orderByColumn = ""
      for (let i = 0; i < this.orderBys.length; i++) {
        if (i>0){
          orderByColumn += " , "
        }
        if (i==this.orderBys.length-1){
          orderByColumn += this.orderBys[i].column + ' '
          this.queryParams.isAsc = this.orderBys[i].direction.toLowerCase()
        }else {
          orderByColumn += this.orderBys[i].column+ ' ' +this.orderBys[i].direction.toLowerCase() +"  "
        }
      }
      this.queryParams.orderByColumn =orderByColumn
      this.getList()
    },
    /** 打印  */
    print(){
      let printData = this.printData
      printData.list = this.tableData
      if(JSON.stringify(this.tableData) === "[]"){
        this.$message.error("无数据可打印,请重新查询")
        return;
      }
      let reduceType = this.queryParams.reduceType
      let reduceTypeName =''
      if (reduceType === '4') {
        reduceTypeName ='中药库'
      }
      if (reduceType === '7') {
        reduceTypeName ='西药库'
      }
      printData.title= '制剂室原材料消耗明细';
      printData.timeMap = this.queryParams.startTime.replace('00:00:00','') + '至' + this.queryParams.endTime.replace('23:59:59','')
      printData.workerName= this.$store.state.user.nickName;
      printData.printDate=  new Date()


      console.log(JSON.stringify(printData))
      let file = "/grf/preparationRawMaterialConsumption.grf"
      debugger
      run_print("preview",file,printData)
    },

    /**  导出  */
    excelExport() {
      let dateRange = this.queryParams.dateRange
      if (!dateRange || dateRange.length == 0) {
        this.$message.error("时间区间未选择")
        return;
      }

      this.queryParams.startTime = this.queryParams.dateRange[0]
      this.queryParams.endTime = this.queryParams.dateRange[1]
      let downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
      preparationRawMaterialConsumptionExportRequest(this.queryParams).then(res => {
        downloadYsglByFileName(res.msg, `制剂原材料消耗.xlsx`).then(res => {
          downloadLoadingInstance.close()
        }).catch(es => {
          downloadLoadingInstance.close()
        })

      }).catch(e => {
        downloadLoadingInstance.close()
        console.log(e)
      });

    }
  }
}
</script>

<style>



.el-icon-my-print{
  background: url('/svg/print.svg') center no-repeat;
  font-size: 20px;
  background-size: cover;
}
.el-icon-my-print:before{
  content: "66ff";
  font-size: 10px;
  visibility: hidden;
}
.el-icon-my-export{
  background: url('/svg/export.svg') center no-repeat;
  font-size: 20px;
  background-size: cover;
}
.el-icon-my-export:before{
  content: "66ff";
  font-size: 10px;
  visibility: hidden;
}

</style>
